import numpy as np
import matplotlib.pyplot as plt

def read_correlations(file_path):
    correlations = {}
    max_tr = max_tc = 0
    with open(file_path, 'r') as f:
        for line in f:
            filename, value = line.strip().split(':')
            value = round(float(value), 1)  # 保留小数点后一位
            tr, tc = filename.split('.')[0].split('-')
            tr = int(tr[2:])
            tc = int(tc[2:])
            correlations[(tr, tc)] = value
            max_tr = max(max_tr, tr)
            max_tc = max(max_tc, tc)
    return correlations, max_tr, max_tc

def plot_correlations(correlations, num_rows, num_cols):
    data = np.zeros((num_rows, num_cols))
    for (tr, tc), value in correlations.items():
        data[tr - 1, tc - 1] = value  # 将行列从1转换为从0开始的索引

    fig, ax = plt.subplots()
    cax = ax.matshow(data, cmap='coolwarm')
    fig.colorbar(cax)

    for (i, j), value in np.ndenumerate(data):
        if value != 0:
            display_value = f'{value:.1f}'.lstrip('0')  # 去掉前导0
            ax.text(j, i, display_value, ha='center', va='center', color='black')

    ax.set_xticks(np.arange(num_cols))
    ax.set_yticks(np.arange(num_rows))
    ax.set_xticklabels(np.arange(1, num_cols + 1))  # 调整列坐标标签从 1 开始
    ax.set_yticklabels(np.arange(1, num_rows + 1))  # 调整行坐标标签从 1 开始

    plt.xlabel('Column (tc)')
    plt.ylabel('Row (tr)')
    plt.title('Pearson Correlations')
    plt.show()

# 读取相关性数据
correlation_file = 'filtered_correlations2.txt'
correlations, num_rows, num_cols = read_correlations(correlation_file)

# 绘制网格图
plot_correlations(correlations, num_rows, num_cols)
